// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
import * as vscode from 'vscode';

// This method is called when your extension is activated
// Your extension is activated the very first time the command is executed
export function activate(context: vscode.ExtensionContext) {

	// Use the console to output diagnostic information (console.log) and errors (console.error)
	// This line of code will only be executed once when your extension is activated
	console.log('Congratulations, your extension "vscode-text-replacer" is now active!');

	// The command has been defined in the package.json file
	// Now provide the implementation of the command with registerCommand
	// The commandId parameter must match the command field in package.json
	const disposable = vscode.commands.registerCommand('excelColumnToNumber', () => {
		// The code you place here will be executed every time your command is executed
		// Display a message box to the user
		replaceSelectedText();
	});

	context.subscriptions.push(disposable);
}

// 替换函数
function replaceSelectedText() {
	const editor = vscode.window.activeTextEditor;
	if (!editor) {
		vscode.window.showErrorMessage('No active editor found!');
		return;
	}

	const selection = editor.selection;
	const selectedText = editor.document.getText(selection);

	if (!selectedText) {
		vscode.window.showErrorMessage('No text selected!');
		return;
	}

	if (!/^[a-zA-Z]+$/.test(selectedText)) {
		vscode.window.showErrorMessage('Need select English letter!');
		return;
	}

	editor.edit(editBuilder => {
		const replacement = excelColumnToNumber(selectedText);
		editBuilder.replace(selection, replacement);
		vscode.window.showInformationMessage('success!');
	});
}

function excelColumnToNumber(column: string): string {
	column = column.toLocaleUpperCase();
	let result: number = 0;
	for (let i = 0; i < column.length; i++) {
		const charCode = column.charCodeAt(i) - 64; // 'A' 的 ASCII 码是 65
		result = result * 26 + charCode;
	}
	return `${result}`;
}

// This method is called when your extension is deactivated
export function deactivate() { }
